package org.budo.support.mvcs;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * @author limingwei 请使用 Spring 的 RequestContextListener
 */
public class MvcsFilter implements Filter {
    private static final Logger log = Slf4j.getLogger();

    private static final ThreadLocal<HttpServletRequest> REQUEST_THREAD_LOCAL = new InheritableThreadLocal<HttpServletRequest>();

    private static final ThreadLocal<HttpServletResponse> RESPONSE_THREAD_LOCAL = new InheritableThreadLocal<HttpServletResponse>();

    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("#26 init, " + this);
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        REQUEST_THREAD_LOCAL.set((HttpServletRequest) request);
        RESPONSE_THREAD_LOCAL.set((HttpServletResponse) response);

        chain.doFilter(request, response);

        REQUEST_THREAD_LOCAL.remove();
        RESPONSE_THREAD_LOCAL.remove();
    }

    public static HttpServletRequest getRequest() {
        return REQUEST_THREAD_LOCAL.get();
    }

    public static HttpServletResponse getResponse() {
        return RESPONSE_THREAD_LOCAL.get();
    }

    public void destroy() {
        log.info("#36 destroy, " + this);
    }
}
